<?php

/**
 * Base class for all service interface 
 */
class CServiceController extends CCommonController {

    protected $clientId;
    protected $clientToken;
    protected $callbackUrl;
    protected $parameter;
    protected $requestRecord;
    protected $reply = array('reason' => "", 'success' => false);

    /**
     * Pemrosesan awal sebuah service request
     * @throws CHttpException 
     */
    public function init() {
        parent::init();

        $this->parameter = $_GET;
        $param = $this->parameter;

        if (/*!isset($param['clientid']) ||*/ !isset($param['clienttoken'])) {
            //TODO: Fix HTTP code
            throw new CHttpException(400, "Access denied");
        } else {
            //$this->clientId = $param['clientid'];
            $this->clientToken = $param['clienttoken'];
            $this->callbackUrl = $param['callbackurl'];

            if (!$this->isClientAuthorized()) {
                //TODO: Fix HTTP code
                throw new CHttpException(400, "Access denied");
            }

            $this->savePersistent();
        }
    }

    protected function setReply($success, $reason) {
        $this->reply['success'] = $success;
        $this->reply['reason'] = $reason;
    }

    protected function beforeAction($action) {
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');    // cache for 1 day
        }

        // Access-Control headers are received during OPTIONS requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

            exit(0);
        }
        
        return parent::beforeAction($action);
    }

    protected function afterAction($action) {
        //echo "<pre>";
        //print_r($this->reply);
        echo json_encode($this->reply);
        //echo "</pre>";
        parent::afterAction($action);
    }

    protected function setReplyAttribute($attr, $val) {
        $this->reply[$attr] = $val;
    }

    /**
     * Menulis semua service request ke persistent database 
     */
    private function savePersistent() {
        $request = ServiceRequest::createFromRequest(Yii::app()->request, $this->parameter);
        $request->save();
        $this->requestRecord = $request;
    }

    /**
     * Menguji apakah klien terautorisasi
     */
    protected function isClientAuthorized() {
        return Client::isAuthorized($this->clientToken);
    }

}

?>
